package com.xuruzi.demo.controller;

import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.xuruzi.demo.service.DutyService;
import com.xuruzi.demo.util.BaseMsg;
import com.xuruzi.demo.util.WxUtils;
import com.xuruzi.demo.util.response.TextMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by xuruzi on 2020/3/27.
 */
@RestController
@RequestMapping("/weixin")
public class ReceiveMsgController {
    private static final Logger logger = LoggerFactory.getLogger(ReceiveMsgController.class);

    @Autowired
    DutyService dutyService;

    @GetMapping
    public String processGet(@RequestParam(name = "msg_signature", required = false) String signature,
                            @RequestParam(name = "timestamp", required = false) String timestamp,
                            @RequestParam(name = "nonce", required = false) String nonce,
                            @RequestParam(name = "echostr", required = false) String echostr){
        logger.info("校验回调url......");
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxUtils.getToken(), WxUtils.getsEncodingAESKey(), WxUtils.getCorpId());

            String smsgignature = URLDecoder.decode(signature,"UTF-8");
            String stimestamp = URLDecoder.decode(timestamp, "UTF-8");
            String snonce = URLDecoder.decode(nonce, "UTF-8");
            String sechostr = URLDecoder.decode(echostr, "UTF-8");
            return wxcpt.VerifyURL(smsgignature, stimestamp,
                    snonce, sechostr);
        }catch (Exception e){
            logger.info("{}",e);
        }
        return null;
    }

    @PostMapping
    public void processPost(HttpServletRequest request, HttpServletResponse response){
        logger.info("校验回调url......2");
        if(WxUtils.checkSignature(request)) {
            Map reqMap = WxUtils.parseXml(request);
            String fromUserName = (String) reqMap.get("FromUserName");
            String toUserName = (String) reqMap.get("ToUserName");
            String msgType = (String) reqMap.get("MsgType");
            logger.info("收到消息,消息类型:{}", msgType);
            String result = "";
            TextMsg replyMsg = null;
            if (msgType.equals("text")) {
                result = (String) reqMap.get("Content");
                logger.info("接收到文本消息内容:{}", result);

                replyMsg = (TextMsg) handTextMsg(new TextMsg(result));//自动回复
                replyMsg.setMsgId((String) reqMap.get("MsgId"));
                replyMsg.setMsgType((String) reqMap.get("MsgType"));
                replyMsg.setAgentId((String) reqMap.get("AgentId"));
                replyMsg.setFromUserName((String) reqMap.get("FromUserName"));
                replyMsg.setToUserName((String) reqMap.get("ToUserName"));
                replyMsg.setCreateTime(Long.parseLong((String) reqMap.get("CreateTime")));

                result = replyMsg.toXml();
                logger.info("回复内容明文:{}", result);
                try {
                    WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxUtils.getToken(), WxUtils.getsEncodingAESKey(), WxUtils.getCorpId());
                    result = wxcpt.EncryptMsg(result, request.getParameter("timestamp"), request.getParameter("nonce"));
                    logger.info("回复内容加密密文:{}", result);
                    response.setContentType("text/xml;charset=UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(result);
                    writer.close();
                } catch (Exception e) {

                }
            }
        }

    }

    /**
     * 处理接收的文本消息
     * @param msg
     * @return
     */
    private BaseMsg handTextMsg(TextMsg msg){
        //自动回复"值班"关键字
        if("值班".equals(msg.getContent())){
            return new TextMsg(dutyService.getDutyName());
        }

        return null;
    }


}
